package com.gel.shortLink.admin.common.biz;

import com.alibaba.fastjson2.JSON;
import com.gel.shortLink.admin.common.enums.UserErrorCodeEnum;
import com.gel.shortLink.admin.convention.exception.ClientException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@RequiredArgsConstructor
@Component
public class UserTransmitHandler implements HandlerInterceptor {


    private  final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = request.getHeader("username");
        String token = request.getHeader("token");
        Object user = stringRedisTemplate.opsForHash().get("login_" + username, token);
        if(user == null){
            throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
        }
        UserInfoDTO userInfoDTO = JSON.parseObject(user.toString(), UserInfoDTO.class);
        UserContext.setUser(userInfoDTO);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
